package top.jacktgq.itheima.netty.protocol_design.groupchat.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import top.jacktgq.itheima.netty.protocol_design.groupchat.client.handler.ClientMessageHandler;
import top.jacktgq.itheima.netty.protocol_design.groupchat.message.PingMessage;
import top.jacktgq.itheima.netty.protocol_design.groupchat.protocol.MessageCodecSharable;
import top.jacktgq.itheima.netty.protocol_design.groupchat.protocol.ProtocolFrameDecoder;

import java.util.Scanner;
import java.util.concurrent.CyclicBarrier;

/**
 * @Author CandyWall
 * @Date 2021/3/23--14:49
 * @Description
 */
@Slf4j
public class ChatClient {
    public static void main(String[] args) throws InterruptedException {
        LoggingHandler loggingHandler = new LoggingHandler(LogLevel.DEBUG);
        // MessageCodec messageCodec = new MessageCodec();
        MessageCodecSharable messageCodec = new MessageCodecSharable();

        Scanner scanner = new Scanner(System.in);

        // 回环栅栏：接收用户登录的用户名和密码后的输入线程先通过该锁先阻塞住，
        // 等待NIO线程获取到登录的结果后再决定 后续是尝试继续登录 还是 登录成功打印用户聊天选择菜单
        CyclicBarrier WAIT_FOR_LOGIN = new CyclicBarrier(2);

        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast(new ProtocolFrameDecoder())
                                .addLast(loggingHandler)
                                .addLast(messageCodec)
//                                .addLast(loggingHandler)
                                // 如果6s内没有向服务器写数据，就会触发写事件
                                .addLast(new IdleStateHandler(0, 6, 0))
                                // 可以同时作为入站和出站处理器
                                .addLast(new ChannelDuplexHandler() {
                                    @Override
                                    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                                        // 判断是否是IdleStateEvent事件（用于触发用户事件，包含读空闲，写空闲，读写空闲）
                                        if (evt instanceof IdleStateEvent) {
                                            IdleStateEvent event = (IdleStateEvent) evt;
                                            if (event.state() == IdleState.READER_IDLE) {
                                                System.out.println("进入读空闲...");
                                            } else if (event.state() == IdleState.WRITER_IDLE) {
                                                System.out.println("进入写空闲...向服务器发送心跳包");
                                                // 向服务器发送心跳包
                                                ctx.writeAndFlush(new PingMessage());
                                            } else if (event.state() == IdleState.ALL_IDLE) {
                                                System.out.println("进入读写空闲...关闭连接");
                                                //ctx.channel().close();
                                            }
                                        }
                                    }
                                })
                                .addLast("Client Handler", new ClientMessageHandler(scanner, WAIT_FOR_LOGIN));
                    }
                })
                .connect("localhost", 6666);
        /*channelFuture.channel().closeFuture().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                // 客户端关闭
                log.debug("客户端正在关闭...");
                group.shutdownGracefully();
                log.debug("客户端关闭成功！");
            }
        });*/
        // 监听客户端连接事件
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                log.debug("客户端连接成功... {}" + channelFuture.channel());
                // 监听客户端SocketChannel关闭事件，关闭客户端事件循环组中的事件循环
                channelFuture.channel().closeFuture().addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        // 客户端关闭
                        log.debug("客户端正在关闭...");
                        group.shutdownGracefully();
                        log.debug("客户端关闭成功！");
                    }
                });
            }
        });

    }

}
